import mqtt from "@/utils/mqtt.min.js"

class mqttHandle {
	constructor() {
		this.connect = {
			host: "test.jiaoguanyi.cn",
			port: 443, // 这里用了ngnix反向代理解决wss连接异常的问题
			endpoint: "/mqtt",
			clean: true, // 保留会话
			cleanSession: true,
			connectTimeout: 7000, // 超时时间 ms
			reconnectPeriod: 7000, // 重连时间间隔 ms
			// 认证信息
			clientId: Number(new Date()).toString(),
			username: "",
			password: "",
		}
		// this.subscription = {
		// 	topic: subscribe, //需要传入数组的包含订阅的名称
		// 	qos: 0,
		// }
		this.mqttClient = null;
	}

	/**
	 * 创建链接
	 * @returns client
	 */
	createConnect() {
		try {
			const {
				host,
				port,
				endpoint,
				...options
			} = this.connect;
			const connectUrl = `wxs://${this.connect.host}:${this.connect.port}${this.connect.endpoint}`;
			this._client = mqtt.connect(connectUrl, options);
			this._client.on("connect", () => {
				console.log("Connection succeeded!");
			});
			this._client.on('reconnect', (error) => {
				console.log('正在重连', error)
			})
			this._client.on("error", (error) => {
				console.log("Connection failed", error);
			});
			// //配置topic
			// const {topic, qos} = this.subscription;
			// this._client.subscribe(topic, {qos: qos}, (error, res) => {
			//   if (error) {
			//     console.log("Subscribe to topics error", error);
			//     return;
			//   }
			// });
			this.mqttClient = this._client;
			return this.mqttClient;
		} catch (error) {
			console.log("mqtt.connect error", error);
		}

	}

	subscribe(topic) {
		if (this.mqttClient == null) {
			console.log("客户端初始化失败");
			return;
		}
		this.mqttClient.subscribe(topic, {
			qos
		}, (error, res) => {
			if (error) {
				console.log("Subscribe to topics error", error);
				return;
			}
		});
	}

}

export default mqttHandle;